/**
 * SocketStreamにforeachを拡張
 */
module nazo.socketstream;
import std.socketstream, std.socket, std.stream, std.stdio;

class SocketStream:std.socketstream.SocketStream{
  const uint buffsize=500;
  this(Socket sock,uint buffsize=buffsize.init){
    super(sock);
  }
  this(Socket sock,FileMode mode,uint buffsize=buffsize.init){
    super(sock,mode);
  }
  alias std.socketstream.SocketStream.opApply opApply;
  int opApply(int delegate(inout ubyte[] buff) dg){
    int result = 0;
    ubyte[] buf=new ubyte[buffsize];
    while((buf.length=read(buf))>0){
//      std.stdio.writefln(buf.length);
      result = dg(buf);
      if (result)
        break;
      buf.length=buffsize;
    }
    return result;
  }
}

import std.stdio, std.string;

unittest{
  auto ih=new InternetHost;
  ih.getHostByName("www.ietf.org");
  auto ia = new InternetAddress(ih.addrList[0], 80);
  auto tcp = new TcpSocket(ia.addressFamily());
  tcp.connect(ia);
  auto sock = new SocketStream(tcp);
  sock.write(cast(ubyte[])"GET /home.html\r\nAccept-Language: ja-jp,ja;q=0.8,en-us;q=0.5,en;q=0.3\r\n\r\n");
  ubyte[] data;
  foreach(ubyte[] buf;sock){
    data~=buf;
  }
  assert(find(cast(string)data,"<html")>=0);
  assert(find(cast(string)data,"</html>")>=0);
  sock.close();
}
